<template>
  <div>
    <el-card class="scheduled_card">
      <div slot="header">
        <span>表达式例子</span>
      </div>
      <div>
        "0 0 12 * * ?" 每天中午12点触发<br/>
        "0 15 10 ? * *" 每天上午10:15触发<br/>
        "0 15 10 * * ?" 每天上午10:15触发<br/>
        "0 15 10 * * ? 2005" 2005年的每天上午10:15触发<br/>
        "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发<br/>
        "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发<br/>
        "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发<br/>
        在线验证地址：<a href="https://cron.qqe2.com/" target="_blank">https://cron.qqe2.com</a>
      </div>
    </el-card>
    <table-search :searchOptions="searchOptions" :searchSource="searchSource"
     @searchHandle="searchHandle" @resetHandle="resetHandle">
      <template slot="table-search_behind">
        <el-button v-if="isAuth('scheduled:task:save')" type="primary" icon="el-icon-edit" :size="searchOptions.size" @click="addHandle()">新增</el-button>
      </template>
    </table-search>
    <table-content ref="table" :tableOptions="tableOptions" :tableSource="tableSource" @selectionChangeHandle="selectionChangeHandle"
     @sortChangeHandle="sortChangeHandle" @pageHandle="pageHandle">
    </table-content>
    <scheduled-info ref="scheduledInfoDialog" :size="this.size" @flush="flush"></scheduled-info>
    <scheduled-log-window ref="scheduledLogWindowDialog" :size="this.size"></scheduled-log-window>
  </div>
</template>

<script>
import TableSearch from '@/components/table/table-search'
import TableContent from '@/components/table/table-content'
import ScheduledInfo from '@/views/modules/scheduled/scheduled-info'
import ScheduledLogWindow from '@/views/modules/scheduled/scheduled-log-window'
import { getScheduledListApi, deleteScheduledApi, updateScheduledStatusApi } from '@/api/scheduled'

export default {
  components: { TableSearch, TableContent, ScheduledInfo, ScheduledLogWindow },
  props: {
    size: {
      type: String,
      default: 'mini'
    }
  },
  data() {
    return {
      searchOptions: {
        size: this.size,
        show: true,
        init: true
      },
      tableOptions: {
        size: this.size,
        highlightCurrentRow: true, // 是否要高亮当前行
        fit: true, // 列的宽度是否自撑开
        mutiSelect: true, // 是否显示选择框
        pagination: true // 是否分页
      },
      searchSource: {
        inModel: {
          name: '',
          status: ''
        },
        operations: [
          {
            name: '任务名',
            key: 'name',
            type: 'text',
            width: '9rem',
            length: 10
          },
          {
            name: '状态',
            key: 'status',
            type: 'select',
            width: '7rem',
            list: [
              { key: '未启用', value: '0' },
              { key: '运行', value: '1' },
              { key: '停止', value: '2' }
            ]
          },
          {
            type: 'place',
            width: '45rem'
          }
        ]
      },
      tableSource: {
        headers: [
          {
            prop: 'createTime',
            label: '创建时间',
            width: '150px',
            sortable: 'custom',
            formatData: (row, column, columnValue) => {
              return this.$time.formatDate(columnValue, 'yyyy-MM-dd HH:mm:ss')
            }
          },
          {
            prop: 'updateTime',
            label: '修改时间',
            width: '150px',
            sortable: 'custom',
            formatData: (row, column, columnValue) => {
              return this.$time.formatDate(columnValue, 'yyyy-MM-dd HH:mm:ss')
            }
          },
          {
            prop: 'name',
            label: '任务名',
            route: {
              type: 0,
              field: 'id',
              method: (data) => {
                this.viewHandle(data)
              }
            }
          },
          { prop: 'cron', label: '表达式' },
          {
            prop: 'statusDesc',
            label: '状态',
            minWidth: '50px',
            tag: {
              prop: 'status',
              filter: (val) => {
                let data = {
                  '0': 'primary',
                  '1': 'success',
                  '2': 'warning'
                }
                return data[val]
              }
            }
          },
          {
            prop: 'executionStatusDesc',
            label: '执行状态',
            minWidth: '50px',
            tag: {
              prop: 'executionStatus',
              filter: (val) => {
                let data = {
                  '0': 'info',
                  '1': 'primary',
                  '2': 'warning',
                  '3': 'success',
                  '4': 'danger'
                }
                return data[val]
              }
            }
          },
          {
            prop: 'executionLastTime',
            label: '最后执行时间',
            width: '150px',
            formatData: (row, column, columnValue) => {
              if (!columnValue) return ''
              return this.$time.formatDate(columnValue, 'yyyy-MM-dd HH:mm:ss')
            },
            route: {
              type: 0,
              field: 'id',
              method: (data) => {
                this.viewLogWindowHandle(data)
              }
            }
          },
          {
            operation: true,
            width: '200rem',
            operations: [
              {
                label: '启动',
                type: 'primary',
                plain: true,
                permission: 'scheduled:task:monitor',
                method: (index, row) => {
                  this.updateStateHandler(index, row, 1)
                }
              },
              {
                label: '停止',
                type: 'warning',
                plain: true,
                permission: 'scheduled:task:monitor',
                method: (index, row) => {
                  this.updateStateHandler(index, row, 2)
                }
              },
              {
                label: '删除',
                type: 'danger',
                icon: 'el-icon-delete',
                show: true,
                permission: 'scheduled:task:delete',
                method: (index, row) => {
                  this.delHandle(index, row)
                }
              }
            ]
          }
        ],
        data: []
      },
      query: {
        sortField: '',
        sortRule: 1,
        page: 1,
        pageSize: 10,
        name: '',
        status: ''
      },
      selections: []
    }
  },
  created() {
    this.list(this.query)
  },
  methods: {
    list(data) {
      getScheduledListApi(data).then(res => {
        this.tableSource.data = res.data
        this.tableSource.data.content.forEach(item => {
          if (item.status === 0 || item.status === 2) {
            if (item.showButtonIndexs === undefined) {
              item.showButtonIndexs = []
            }
            item.showButtonIndexs.push(0)
            if (item.protect && !this.isAuth('scheduled:task:protect')) {
              if (item.disabledButtonIndexs === undefined) {
                item.disabledButtonIndexs = []
              }
              item.disabledButtonIndexs.push(2)
            }
          } else {
            if (item.showButtonIndexs === undefined) {
              item.showButtonIndexs = []
            }
            item.showButtonIndexs.push(1)
            if (item.disabledButtonIndexs === undefined) {
              item.disabledButtonIndexs = []
            }
            item.disabledButtonIndexs.push(2)
          }
        })
      })
    },
    flush() {
      this.list(this.query)
    },
    searchHandle(obj) {
      this.query.page = obj.page
      Object.assign(this.query, obj.backData)
      this.list(this.query)
    },
    resetHandle() {
      Object.assign(this.$data.query, this.$options.data().query)
      this.$refs.table.init()
      this.list(this.query)
    },
    selectionChangeHandle(obj) {
      this.selections = obj.backData
    },
    sortChangeHandle(obj) {
      let column = obj.backData
      if (column.order) {
        this.query.sortField = column.prop
        // 倒序
        if (column.order === 'descending') {
          this.query.sortRule = 1
        } else {
          this.query.sortRule = 0
        }
      } else {
        // 不排序
        this.query.sortField = ''
        this.query.sortRule = 0
      }
      this.list(this.query)
    },
    pageHandle(obj) {
      this.query.page = obj.backData.page
      this.query.pageSize = obj.backData.pageSize
      this.list(this.query)
    },
    // 查看
    viewHandle (id) {
      this.$refs.scheduledInfoDialog.dialogOptions.show = true
      this.$refs.scheduledInfoDialog.init(1, id)
    },
    // 查看日志窗口
    viewLogWindowHandle (id) {
      this.$refs.scheduledLogWindowDialog.dialogOptions.show = true
      this.$refs.scheduledLogWindowDialog.init(id)
    },
    // 状态改变
    updateStateHandler (index, row, state = 0) {
      let stateMsg = state === 1 ? '启动' : '停止'
      updateScheduledStatusApi(row.id, state).then(res => {
        let data = res.data

        this.$set(row, 'updateTime', data.updateTime)
        this.$set(row, 'status', data.status)
        this.$set(row, 'statusDesc', data.statusDesc)
        this.$set(row, 'executionLastTime', data.executionLastTime)
        this.$set(row, 'executionStatus', data.executionStatus)
        this.$set(row, 'executionStatusDesc', data.executionStatusDesc)

        if (data.result) {
          this.$set(row, 'showButtonIndexs', state === 1 ? [1] : [0])
          this.$message({
            message: stateMsg + '成功',
            type: 'success',
            duration: 1500
          })
        } else {
          this.$set(row, 'showButtonIndexs', state === 1 ? [0] : [1])
          this.$message({
            message: stateMsg + '失败，请点击执行时间通过控制台查看详情',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(() => {
        this.$message({
          message: stateMsg + '失败',
          type: 'error',
          duration: 1500
        })
      })
    },
    // 删除
    delHandle (index, row) {
      deleteScheduledApi(row.id).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1500
        })
        this.list(this.query)
      }).catch(() => {
        this.$message({
          message: '删除失败',
          type: 'error',
          duration: 1500
        })
      })
    },
    // 新增
    addHandle () {
      this.$refs.scheduledInfoDialog.dialogOptions.show = true
      this.$refs.scheduledInfoDialog.init(0)
    }
  }
}
</script>

<style lang="scss" scoped>
  .scheduled {
    &_card {
      text-align: left;
      margin-bottom: 5px;
      >.el-card__header {
        padding: 8px 20px !important;
      }
    }
  }
</style>
